<?php


namespace app\index\controller;


use app\common\controller\Frontend;
use fast\CcProxy;
use think\App;
use think\Cache;

class Card extends Frontend
{
    protected $noNeedLogin = ["*"];
    
    
    private function locked($card)
    {
        if (!Cache::get($card)) {
            Cache::set($card, true, 1000);
        } else {
            $this->error("当前卡密正在充值中");
        }
    }


    public function index()
    {
        $account = $this->request->param('account', null);
        $code = $this->request->param('code', null);

        if (empty($account)) {
            $this->error("充值账号不能为空");
        }

        if (empty($code)) {
            $this->error("充值卡密不能为空");
        }

        $card = model('app\admin\model\card\Index')->with('apps')->where("code", $code)->find();

        if (!$card) {
            $this->error("卡密不存在");
        }

        if ($card->status) {
            $this->error("卡密已被充值");
        }

        $this->locked($card);

        $cc = new CcProxy($card->apps->domain, $card->apps->account, $card->apps->password);

        $getUser = function () use ($cc, $account, $card) {
            $users = array_filter($cc->index(), function ($val) use ($account) {
                return $val['userid'] == $account;
            });

            if (count($users) == 0) {
                $this->unlock($card);
                $this->error("账号不存在");
            }
            elseif (count($users) > 1) {
                $this->unlock($card);
                $this->error("该账户不合法，禁止充值");
            }
            else{
                $users = array_values($users);
            }
            return $users[0];
        };

        $user = $getUser();


        // 判断是否到期
        $oldDate = $user['disabledate'] . " " . $user['disabletime'];
        $disableTime = $user['disabletime'];

        // 已经过期
        if (strtotime($oldDate) < time()) {
            $disableDate = date('Y-m-d', strtotime("+{$card['day']} day"));
            $disableTime = date('H:i:s');
        } else {
            $disableDate = date('Y-m-d', strtotime("+{$card['day']} day", strtotime($user['disabledate'])));
        }
        $cc->edit($user['userid'], $user['username'], $user['password'], $user['enable'], $user['autodisable'], $user['usepassword'], $disableDate, $disableTime);

        $newUser = $getUser();

        $this->unlock($card);
        if ($newUser['disabledate'] != $user['disabledate']) {
            $card->save([
                'status' => 1,
                "apply_date" => time(),
                "account" => $account
            ]);
            $this->success("充值成功");
        }

        $this->success("充值失败");
    }

    public function register()
    {
        $data = $this->request->post();
        $validate = $this->validate($data, [
            'account' => "require|min:2|max:12",
            'password' => "require|min:3|max:8",
            'code' => "require|max:32",
            'qq' => "require|min:5|max:11"
        ], [
            "account.require" => "账号不能为空",
            "account.min" => "账号长度最小2位",
            "account.max" => "账号长度最大12位",
            "password.require"  => "密码不能为空",
            "password.min"  => "密码长度最小3位",
            "password.max"  => "密码长度最大8位",
            "code.require"  => "卡密不能为空",
            "code.max" => "卡密长度最大32位",
            "qq.require" => "QQ为必填项",
            "qq.min" => "QQ长度有误",
            "qq.max" => "QQ长度有误"
        ]);

        if (true !== $validate) {
            $this->error($validate);
        }
        
        $code = $data['code'];
        $account = $data['account'];
        $password = $data['password'];
        $qq = $data['qq'];
		        
        if ($account == 'admin') {
            $this->error("管理员账号,禁止注册！");
        }
        
        $card = model('app\admin\model\card\Index')->with('apps')->where("code", $code)->find();

        if (!$card) {
            $this->error("卡密不存在");
        }

        if ($card->status) {
            $this->error("卡密已被充值");
        }

        $this->locked($card);
        $cc = new CcProxy($card->apps->domain, $card->apps->account, $card->apps->password);


        // 检查用户名
        $users = array_filter($cc->index(), function ($val) use ($account) {
            return $val['userid'] == $account;
        });

        if (count($users) > 0) {
            $this->unlock($card);
            $this->error("已经存在该账号");
        }

        $disableDate = date('Y-m-d', strtotime("+{$card['day']} day"));


        // 注册用户
        $cc->add($account, $password, $disableDate, date("H:i:s"));

        $users = array_filter($cc->index(), function ($val) use ($account) {
            return $val['userid'] == $account;
        });

        $this->unlock($card);

        if (count($users) == 0) {
            $this->error("账号注册失败，卡密使用失败！");
        }
        else{
            $card->save([
                'status' => 1,
                "apply_date" => time(),
                "account" => $account,
                'qq' => $qq,
            ]);
        $this->success("账号注册成功，卡密使用成功！");
        }
    }

    public function query()
    {
        $data = $this->request->post();
        $validate = $this->validate($data, [
            'account' => "require|min:2|max:12",
            'appId' => "require|integer",
        ], [
            "account.require" => "账号不能为空",
            "account.min" => "账号长度最小2位",
            "account.max" => "账号长度最大12位",
            "appId.require" => "请选择一个有效应用",
            "appId.integer" => "应用选择有误",
        ]);

        if (true !== $validate) {
            $this->error($validate);
        }

        $app = model('app\admin\model\card\Apps')->where("id", $data['appId'])->find();

        if (!$app) {
            $this->error("应用不存在");
        }

        $cc = new CcProxy($app->domain, $app->account, $app->password);

        // 检查用户名
        $users = array_filter($cc->index(), function ($val) use ($data) {
            return $val['userid'] == $data['account'];
        });

        if (count($users) == 0) {
            $this->error("账号不存在");
        }

        if (count($users) > 1) {
            $this->error("该账户不合法");
        }

        $user = array_values($users)[0];

        $this->success("查询成功", '', [
            'date' => $user['disabledate'] . " " . $user['disabletime']
        ]);
    }


    private function unlock($card)
    {
        Cache::rm($card);
    }
}